package com.acoffee.springcloud.consumer.user.controller;

import com.acoffee.springcloud.common.entity.ResponseEntity;
import com.acoffee.springcloud.common.entity.User;
import com.acoffee.springcloud.consumer.user.feign.UserFeignClient;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author acoffee
 * @create 2022-01-20 9:48
 */
//添加自动刷新注解在Controller上
@RefreshScope
@RestController
@RequestMapping("/consumeruser")
public class ConsumerUserController {

//    @Autowired
//    RestTemplate restTemplate;

//    @Autowired
//    DiscoveryClient discoveryClient;

//    String url = "http://localhost:8081/user/";

    //目前使用的调用方式是:RestTemplate+注册中心
//    String getUrl(){
//        List<ServiceInstance> instances = discoveryClient.getInstances("provider-user");
//        ServiceInstance serviceInstance = instances.get(0);
//        return  "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/user/";
//    }

//    String getUrl() {
//        //Ribbon的本质就是restTemplate+@LoadBlanced,自动去注册中心通过名字获取调用地址
//        return "http://provider-user/user/";
//    }

    @Autowired
    UserFeignClient userFeignClient;

    @RequestMapping("/getUserById/{id}")
    public ResponseEntity<User> getUserById(@PathVariable int id) {
        //restTemplate的API实现get远程调用
        return userFeignClient.findById(id);
    }

    @GetMapping("/")
    public ResponseEntity<List<User>> finAll() {
        return userFeignClient.findAll();
    }

    @PostMapping("/addUser")
    public ResponseEntity<Boolean> addUser(User user) {
        return userFeignClient.addUser(user);
    }

    //定义调用当前方法如果出现异常，执行降级方法，降级方法
    //和原来的方法的方法签名一致(访问修饰符、返回值、参数列表)
    @HystrixCommand(fallbackMethod = "timeoutFallback")
    @GetMapping("/timeout")
    public ResponseEntity<String> timeout(){
        System.out.println("进入timeout");
        return userFeignClient.timeout();
    }

    //定义降级方法
    public ResponseEntity<String> timeoutFallback(){
        System.out.println("进入timeoutFallback");
        return new ResponseEntity<String>(50000,"fallback","timeout-allback");
    }

    @GetMapping("/ok")
    public ResponseEntity<String> ok(){
        return userFeignClient.ok();
    }

    @Value("${testconfig}")
    String testconfig;

    @GetMapping("/testConfig")
    public ResponseEntity<String> testConfig(){
        System.out.println("进入timeoutFallback");
        return new ResponseEntity<String>(20000,"testconfig",testconfig);
    }
}
